from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE
from django.core.cache import cache

class AreaView(View):


    def get(self,request):
        #接收area-id

        area_id = request.GET.get('area_id')


        # 若有，查询市、区、县信息
        if area_id is not None:

            sub_list = cache.get('sub_area_%s'%area_id)
            if sub_list is None:

                areas = Area.objects.filter(parent_id=area_id)

                sub_list =[]

                for area in areas:
                    sub_list.append(
                        {
                            'id': area.id,
                            'name':area.name
                        })

                cache.set('sub_area_%s'%area_id,sub_list, 24 * 3600)

            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','sub_list':sub_list})

        else:

            pro_list = cache.get('pro_list')

            if pro_list is None:

                areas = Area.objects.filter(parent = None)

                pro_list =[]

                for area in areas:
                    pro_list.append(
                        {
                            'id':area.id,
                            'name':area.name
                        }
                    )

                cache.set('pro_list',pro_list,24*3600)


            return http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','provinces':pro_list})
        # 没有，省信息


